import axios from "axios";
import NProgress from "nprogress";
import { Notification } from "element-ui";

import store from "../store";

const service = axios.create({
  baseURL: process.env.VUE_APP_API,
  timeout: 10 * 60 * 1000
});

service.defaults.headers["Content-type"] = "application/json";
service.interceptors.request.use(
  config => {
    config.headers["token"] = store.getters.getToken || "";
    NProgress.start();
    return config;
  },
  err => {
    console.log("request reject:", err);
    NProgress.done();
    return Promise.resolve(err);
  }
);

service.interceptors.response.use(
  res => {
    NProgress.done();
    //no login in
    if (res.data.code === 1500) {
      store.state.user !== null &&
        Notification.error("当前登录用户过期,请重新登录!");
      store.dispatch("exitLogin");
      return;
    }
    //download file request
    if (res.status === 200 && res.data instanceof Blob) return res.data;
    //normal request
    if (res.data.code === 0) {
      // if (res.data.data === null) return {};
      return res.data.data;
    }
    Notification.error(res.data.msg);//
    console.table({ api: res.config.url, ...res.data });
    return Promise.reject(res.data.msg);
  },
  err => {
    NProgress.done();
    return Promise.reject(err);}

);

export default service;
